首页 > 试题广场 >

四则运算

[编程题]四则运算
  • 热度指数:122270 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
输入一个表达式(用字符串表示),求这个表达式的值。
保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。

数据范围:表达式计算结果和过程中满足 ,字符串长度满足


输入描述:

输入一个算术表达式



输出描述:

得到计算结果

示例1

输入

3+2*{1+2*[-4/(8-6)+7]}

输出

25
print(eval(input()))
抱歉python真的可以为所欲为哈哈哈哈

发表于 2023-01-26 10:55:52 回复(0)
s=input()
t=''
for i in s:
    if i in ['[','{']:
        t+='('
    elif i in [']','}']:
        t+=')'
    elif  i=='/':
        t+='//'
    else:
        t+=i
print(eval(t))

发表于 2022-10-24 00:40:43 回复(0)
s = list(input())
ss = []
dict_op = {')':'(', ']':'[', '}':'{'}
priority = {'+': 1, '-': 1, '*': 2, '/': 2}
i = 0
while i < len(s):
    if ord('0') <= ord(s[i]) <= ord('9'):
        j = i
        temp = ''
        while j < len(s) and ord('0') <= ord(s[j]) <= ord('9'):
            temp += s[j]
            j += 1
        ss.append(int(temp))
        i = j
    else:
        ss.append(s[i])
        i += 1
# 添加结束符
ss.append('#')
        
def process_stack(stack):
    # 操作数
    nums = []
    # 操作符
    ops = []
    # 判断负号和减号,当前一个字符为'('时当作数的一部分,不添加进操作符
    pre = '('
    neg_flag = 1
    for x in stack:
        if type(x) != str&nbs***bsp;ord('0') <= ord(x) <= ord('9'):
            nums.append(int(x) * neg_flag)
            neg_flag = 1
            pre = x
        else:
            if pre == '(':
                neg_flag = -1 if x == '-' else 1
            else:
                ops.append(x)
    # 只有一个操作符,直接返回
    if len(nums) == 1:
        return nums[0]
    while len(nums) > 1:
        if len(ops) == 1:
            # 这时操作符栈中只有一个操作符了,直接输出结果
            num2 = nums.pop(-1)
            num1 = nums.pop(-1)
            op = ops.pop(-1)
            return cal(num1, num2, op)
        elif priority[ops[-1]] >= priority[ops[-2]]:
            num2 = nums.pop(-1)
            num1 = nums.pop(-1)
            op = ops.pop(-1)
            # 如果遇到两个连续减号,需要变号
            if (op == '+'&nbs***bsp;op == '-') and ops[-1] == '-':
                num2 = num2 * -1
            nums.append(cal(num1, num2, op))
        else:
            # 先存栈顶,计算栈顶前一个数
            num_tmp = nums.pop(-1)
            op_tmp = ops.pop(-1)
            num2 = nums.pop(-1)
            num1 = nums.pop(-1)
            op = ops.pop(-1)
            # 还原栈顶
            nums.append(cal(num1, num2, op))
            nums.append(num_tmp)
            ops.append(op_tmp)
    return False


def cal(num1, num2, op):
    if op == '+':
        return num1 + num2
    elif op == '-':
        return num1 - num2
    elif op == '*':
        return num1 * num2
    else:
        return num1 / num2


res = 0
stack = [ss[0]]
i = 1
while len(stack) > 0:
    if ss[i] == '#':
        res = process_stack(stack)
        break    
    if ss[i] != ')' and ss[i] != ']' and ss[i] != '}':
        stack.append(ss[i])
        i += 1
        continue
    t = ss[i]
    # 获取左括号
    vers_op = dict_op[ss[i]]
    sub_stack = []
    while stack[-1] != vers_op:
        sub_stack = [stack.pop(-1)] + sub_stack
    # 弹出左括号
    stack.pop(-1)
    stack.append(process_stack(sub_stack))
    i += 1
print(res)
# print(process_stack("5-3+9*6*(6-10-2)"))
        
折腾了两个小时,艹
发表于 2022-09-04 05:12:14 回复(0)
print(eval(input()))
我这个答案是不是有点过分了😂😂
发表于 2022-08-26 17:26:01 回复(0)
# 分三种情况:
# 1、没有中括号和大括号,直接用eval函数求值
# 2、只有中括号没有大括号,先算中括号,再求值
# 3、既有中括号又有大括号,先算中括号,再算大括号,最后再求值
a = input()
if '[' not in a and ']' not in a and '{' not in a and '}' not in a:
    print(eval(a))
if '['  in a and ']'  in a and '{' not in a and '}' not in a:
    j = a.index('[')
    k = a.index(']')
    b = a.replace(a[j:k + 1], str(int(eval(a[j + 1:k]))))
    print(eval(b))
if '['  in a and ']'  in a and '{'  in a and '}'  in a:
    j = a.index('[')
    k = a.index(']')
    b = a.replace(a[j:k + 1], str(int(eval(a[j + 1:k]))))
    m = b.index('{')
    n = b.index('}')
    c = b.replace(b[m:n + 1], str(int(eval(b[m + 1:n]))))
    print(eval(c))
发表于 2022-08-23 22:38:56 回复(0)
算法是python栈的模板,
但是处理输入太难了,既要考虑负数,还要考虑多位数,参考了两位大佬,终于ac了。
算法是python栈的模板,
但是处理输入太难了,既要考虑负数,还要考虑多位数,参考了两位大佬,终于ac了。
#中缀转后缀
class Stack:
    def __init__(self):
        self.items = []
    def isEmpty(self):
        return self.items == []

    def push(self,item):
        return self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

def infixToPostfix(infixexpr):  #中缀转后缀
    prec = {}
    prec['*'] = 3   #定义运算符的优先级
    prec['/'] = 3
    prec['+'] = 2
    prec['-'] = 2
    prec['('] = 1
    opStack = Stack()    #空栈用来暂存操作符
    postfixList = []    #空表接收后缀表达式
    for token in tokenList:
        if token.isdigit() :
            postfixList.append(token)
        elif token == '(' :
            opStack.push(token)
        elif token == ')' :
            toptoken = opStack.pop()
            while toptoken != '(':
                postfixList.append(toptoken)
                toptoken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and (prec[opStack.peek()]) >= prec[token]:
                postfixList.append(opStack.pop())
            opStack.push(token)
    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return ' '.join(postfixList)

def postfixEval(postfixExpr):   #计算后缀表达式
    operandStack = Stack()
    tokenList = postfixExpr.split()
    for token in tokenList:
        if token.isdigit():
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token,operand1,operand2)
            operandStack.push(result)
    return operandStack.pop()

def doMath(op,op1,op2):     #数***算
    if op == '*':
        return op1*op2
    elif op == '/':
        return op1/op2
    elif op == '+':
        return op1+op2
    else:
        return op1-op2


str = input()
s = str.replace("{", "(").replace("}", ")").replace("]", ")").replace("[", "(").replace(" ", "")
for simbol in ["+", "-", "*", "/", "(", ")"]:
    s = s.replace(simbol, " {} ".format(simbol))
s = s.split()
tokenList = []
for i in range(len(s)):
    if s[i] == '-' and s[i-1] == '(':
        tokenList.append('0')
        tokenList.append(s[i])
    else:
        tokenList.append(s[i])

postfixExpr =  infixToPostfix(tokenList)

print(int(postfixEval(postfixExpr)))

发表于 2022-07-05 20:02:30 回复(0)
while True:
    try:
        raw = input()
        raw = raw.replace("[", "(").replace("]", ")").replace("{", "(").replace("}", ")")
        print(eval(raw))
    except Exception as e:
        break
发表于 2022-06-24 23:15:47 回复(0)
while True:
    try:
        s=input()
        s=s.replace('{', '(')
        s=s.replace("}",")")
        s=s.replace("[","(")
        s=s.replace("]",")")
        print(int(eval(s))) # eval 去掉'',eval是Python的一个内置函数,
        #这个函数的作用是,返回传入字符串的表达式的结果。
    except:
        break

发表于 2022-05-04 02:13:28 回复(0)

print(int(eval(input().replace("{", "(").replace("}", ")").replace("[", "(").replace("]", ")"))))

发表于 2022-04-27 17:09:10 回复(0)
line = input()
line = line.replace('{', '(')
line = line.replace('}', ')')
line = line.replace('[', '(')
line = line.replace(']', ')')
print(int(eval(line)))

发表于 2022-04-03 23:57:38 回复(0)
s = input("")
res = ''
for i in range(len(s)):
    try:
        int(s[i])
        res += int(s[i])
    except:
        if s[i] in ["(", "{", "["]:
            res += ("(")
        elif s[i] in [")", "}", "]"]:
            res += (")")
        else:
            res += (s[i])
print(eval(res))

发表于 2022-03-03 16:42:44 回复(0)
import re
a = input()
b = re.sub(r'\{|\[', '(', a)
c = re.sub(r'\}|\]', ')', b)
print(int(eval(c)))

发表于 2022-02-28 00:54:22 回复(0)
data = input().replace('/','//').replace('{','(').replace('}',')').replace('[','(').replace(']',')')
print(eval(data))
发表于 2022-02-23 23:26:38 回复(0)
while 1:
    try:
        a=input()
        a=a.replace('{','(')
        a=a.replace('[','(')
        a=a.replace('}',')')
        a=a.replace(']',')')
        print(int(eval(a)))
    except:
        break

发表于 2022-02-09 17:12:14 回复(0)
while True:
    try:
        s=input()
        s=s.replace('{', '(').replace("}", ')').replace('[', '(').replace(']', ')')
        s='num='+s
        exec(s)
        exec("""print(int(num))""")
    except:
        break
发表于 2022-02-07 19:24:08 回复(0)

问题信息

难度:
37条回答 46014浏览

热门推荐

通过挑战的用户

查看代码